using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimationComp : BaseComp
{
    [Serializable]
    public class AniClip
    {
        public AniType aniType;
        public AniDir aniDir;
        public Sprite[] aniSprites;
    }

    [SerializeField]
    private AniClip[] _clips;
    [SerializeField]
    private SpriteRenderer _sr;
    [SerializeField]
    private float _duration = 0.4f;

    AniClip _curClip;
    AniType _aniType;
    AniDir _aniDir;
    public void Play(AniType aniType, AniDir aniDir)
    {
        if (_aniType == aniType && _aniDir == aniDir)
            return;

        _aniType = aniType;
        _aniDir = aniDir;
//临时代码
#if true
        if (aniType == AniType.Walk && aniDir == AniDir.Left)
        {
            _sr.flipX = true;
            aniDir = AniDir.Right;
        }
        else if (aniType == AniType.Walk && aniDir == AniDir.Right)
        {
            _sr.flipX = false;
        }
#endif

        foreach (var clip in _clips)
        {
            if(clip.aniType == aniType)
            {
                if(clip.aniDir == aniDir)
                {
                    _curClip = clip;
                    break;
                }
            }
        }

        if (_curClip == null)
        {
            Debug.LogError("Can not find clip aniType:" + aniType + " dir:" + aniDir);
            return;
        }

        if (_coHandle != null)
            StopCoroutine(_coHandle);
        _coHandle = StartCoroutine(CoPlay(_curClip));
    }

    private Coroutine _coHandle = null;
    private IEnumerator CoPlay(AniClip aniClip)
    {
        float t = 0;
        int index = 0;
        _sr.sprite = aniClip.aniSprites[index];
        while (true)
        {
            t += Time.deltaTime;
            if (t > _duration)
            {
                index++;
                if (index > aniClip.aniSprites.Length - 1)
                    index = 0;
                _sr.sprite = aniClip.aniSprites[index];
                t -= _duration;
            }
            yield return null;
        }
        
    }
    // Start is called before the first frame update
    void Start()
    {
        Play(AniType.Idle, AniDir.None);
    }

    // Update is called once per frame
    void Update()
    {

    }
}

